<template>
  <view class="content">
    <view class="user_info">
      <!-- <AtAvatar class="head_img" image='https://jdc.jd.com/img/200'></AtAvatar> -->
      <image class="head_img" :src="userInfo.headimgurl" alt=""></image>
      <view>
        <view class="user_name">{{userInfo.real_name}} ({{userInfo.mobile}})</view>
        <view class="balance">余额：{{cardBalance}}</view>
      </view>
    </view>
    <view class="panel">
      <view class="box">
        <view class="tab">
          充值选项
        </view>
        <view class="No_preferential" v-if="rechangeData == '' || rechangeData.rule.length == 0">
          <!-- <img src="@public/img/pay/zanwuyouhui.png" alt /> -->
          <text>暂无充值项</text>
        </view>
        <view class="preferential" v-else>
          <view
            v-for="(item, index) in rechangeData.rule"
            :class="
              nowIdx == index ? 'rechangeItem rechangeItemActive' : 'rechangeItem'
            "
            :key="index"
            @tap="selectRechange(index)"
          >
            <view class="item item1">充{{ item.charge_money }}元</view>
            <view class="item item2">
              送{{ item.money_status != 0 ? item.money : 0 }}元
            </view>
          </view>
          <view  class="detailsOption" v-if="rechangeData.rule.length != 0">
            {{
              rechangeData.rule[nowIdx].point_status != 0
                ? "赠送" + rechangeData.rule[nowIdx].point + "积分"
                : ""
            }}
            <view v-if="rechangeData.rule[nowIdx].coupon_status != 0">
              <view v-for="(item1, index) in rechangeData.rule[nowIdx].coupon_data" :key="index+'c'">
                {{ "赠送" + item1.couponNum + "张" + item1.title + "优惠券" }}
              </view>
            </view>
            <view v-if="rechangeData.rule[nowIdx].is_unify != 0 || rechangeData.rule[nowIdx].newUnify.length !=0">
              <view v-for="(item, index2 ) in rechangeData.rule[nowIdx].newUnify" :key="index2+'a'">
                {{ "赠送" + item.name + "加油时优惠" + item.money + "元" }}
              </view>
            </view>
            <view v-if="rechangeData.rule[nowIdx].is_lock != 0 || rechangeData.rule[nowIdx].newLock.length !=0">
              <view v-for="(item, index3 ) in rechangeData.rule[nowIdx].newLock" :key="index3+'b'">
                {{ "赠送" + item.name + "加油时每升油价" + item.money + "元" }}
              </view>
            </view>
            <view v-if="rechangeData.rule[nowIdx].first_discount == '1' ">
              <view>首次消费{{rechangeData.rule[nowIdx].first_value}}</view>
            </view>
          </view>
        </view>
        <view class="is_print">
          <AtCheckbox
            :options="checkboxOption"
            :selectedList="checkedList"
            :onChange="handleChangeCheck"
          />
        </view>
        <view class="payment_box">
          <view class="title_line">支付方式</view>
          <view class="payment_item" :class="{payment_select: item.select}" v-for="(item,index) in payment_code" :key="index" @tap="selectPayment(index)">
            <text :class="item.icon"></text>
            <text class="text_size">{{item.name}}</text>
          </view>
        </view>
      </view>
    </view>
    <AtButton class="goButton" @click="submit()">确认支付</AtButton>
    <view class="dialog_body" v-if="showQrcode">
      <view class="top_box"></view>
      <view class="bottom_box">
        <view class="qrcode_box">
          <Canvas id="myQrcode" canvasId="myQrcode"></Canvas>
        </view>
        <view class="qrcode_text">{{qrcode_text}}</view>
        <view class="close_button">
          <AtButton type='primary' @click="closeDialog">关闭</AtButton>
        </view>
      </view>
    </view>
    <AtModal
      :isOpened="showModal"
      confirmText='确认'
      :onClose="handleClose"
      :onConfirm="handleConfirm"
      content='请使用pos机刷卡支付'
    />
  </view>
</template>

<script>
import './option.scss';
import Taro from '@tarojs/taro';
import UserAPI from "../../api/user.js"
import drawQrcode from 'weapp-qrcode';
import { Canvas } from '@tarojs/components';

export default {
  components: {
    Canvas,
  },
  data() {
    return {
      cardList: [],
      userInfo: {},
      checkboxOption: [{value: "1",label: "是否开票"}],
      checkedList: ["1"],
      payment_code: [
        {id: "wxpay", name: "微信", icon: "iconfont icon_size iconweixinzhifu-dp color_wx", select: false},
        {id: "unionpay", name: "支付宝", icon: "iconfont icon_size iconzhifubao color_zfb", select: false},
        {id: "cash", name: "现金", icon: "iconfont icon_size iconxianjin color_xj", select: false},
        {id: "pos", name: "刷卡", icon: "iconfont icon_size iconfaka color_pos", select: false},
      ],
      payment_index: "",
      showQrcode: false,
      qrcode_text: "正在生成二维码",
      showModal: false,
      rechangeData: {
        rule: [
          {
            newUnify: [{
              name: "",
              money: ""
            }],
            newLock: [
              {
                name: "",
                money: ""
              }
            ]
          }
        ],
      },
      nowIdx: 0,
      cardDetails: {},
      ordersn: "",
    }
  },
  mounted(){
    // setTimeout(() => {
    //   this.showQrcode = false;
    // }, 100);
    this.userInfo = Taro.getStorageSync("userInfor");
    this.cardDetails = Taro.getStorageSync("choseCardDetails");
    this.cardBalance = this.cardDetails.balance
    if(this.cardDetails){
      // 获取充值项
      this.init(this.cardDetails);
    }else{
      Taro.redirectTo('/pages/recharge/choseUser');
    }
  },
  methods: {
    // 选择充值项
    selectRechange(index) {
        this.nowIdx = index;
      // this.$emit("sonChose", this.nowIdx);
    },
    async submit(){
      Taro.showToast({title: "正在提交", icon: "loading"});
      var data = {
        account_id: this.cardDetails.id,
        account_type: this.cardDetails.card_type,
        app_id: Taro.getStorageSync('app_id'),
        charge_type: 1,
        key: this.nowIdx,
        // operator_id: Taro.getStorageSync('rechangeStaff'),
        operator_id: Taro.getStorageSync('emp_id'),
        payment_code: this.payment_code[this.payment_index].id,
        recharge_id: this.rechangeData.id,
        receipt_id: this.checkedList.length,
        uid: this.userInfo.uid,
      }
      console.log(data)
      const res = await UserAPI.rechargeSubmit(data);
      if(res.code == 200){
        this.ordersn = res.ordersn;
        if(this.payment_index == 2){
          console.log('现金充值 完成');
          var url = 
            "success?ordersn="+this.ordersn+
            "&money="+this.rechangeData.rule[this.nowIdx].charge_money+
            "&extra="+this.rechangeData.rule[this.nowIdx].money;
          Taro.navigateTo({url: url})
        }else if(this.payment_index == 0 || this.payment_index == 1){ // 微信/支付宝
          this.showQrcode = true;
          const sys = await Taro.getSystemInfo();
          const scale = sys.screenWidth / 375;
          drawQrcode({
            width: 240 * scale,
            height:  240 * scale,
            canvasId: 'myQrcode',
            text: res.data
          });
          this.qrcode_text = '请客户扫码支付'
          this.checkStatus();
        }else if(this.payment_index == 3){ // 刷卡
          this.showModal = true;
          // this.checkStatus();
        }
      }else{
        Taro.showToast({title: res.msg, icon: "none"})
      }
      
    },
    closeDialog(){
      this.showQrcode = false;
    },
    async checkStatus(){
      let pageRoute = Taro.getCurrentPages();
      console.log(pageRoute[pageRoute.length-1].route);
      if(pageRoute[pageRoute.length-1].route != "pages/recharge/option"){
        return false;
      }
      var data = {
        ordersn: this.ordersn
      }
      const res = await UserAPI.rechargeOrderStatus(data);
      if(res.code == 200){
        Taro.showToast({title: "已支付", icon: "success"});
        this.closeDialog();
        setTimeout(() => {
          var url = 
            "success?ordersn="+this.ordersn+
            "&money="+this.rechangeData.rule[this.nowIdx].charge_money+
            "&extra="+this.rechangeData.rule[this.nowIdx].money;
          Taro.navigateTo({url: url})
        }, 1000);
      }else if(res.code == 400) {
        setTimeout(() => {
          this.checkStatus();
        }, 5000);
      }
    },
    init(val){
      let data = {
        token: Taro.getStorageSync('token'),
        app_id: Taro.getStorageSync('app_id'),
        card_id: val.type_card_id,
        card_type: val.card_type //油卡默认写死
      };
      UserAPI.getOilCardsDetail(data).then(res => {
        if (res.code == 200) {
          this.rechangeData = res.data;
          // 每升减，锁油价
          this.rechangeData.rule.forEach(item => {
            item.newUnify = [];
            if (Number(item.is_unify) == 1) {
              // 每升减
              // let cardData
              let cardIndex = item.liter_good_money.findIndex(
                son => son.id == val.type_card_id,
                console.log("val.type_card_id", val.type_card_id)
              );
              item.newUnify = item.liter_good_money[cardIndex].itemArr;
              console.log("cardIndex", cardIndex);
            }
            item.newLock = [];
            if (Number(item.is_lock) == "1") {
              // 每升减
              // let cardData
              let cardIndex = item.lock_good_money.findIndex(
                son => son.id == val.type_card_id
              );
              item.newLock = item.lock_good_money[cardIndex].itemArr;
              console.log("cardIndex", cardIndex);
            }
            let couponIds = item.coupon_ids ? item.coupon_ids.split(",") : []; //优惠券数组id
            if (item.coupon_status != 0) {
              item.coupon_data.forEach(son => {
                son.couponNum = 0;
                couponIds.forEach(grandSon => {
                  if (son.id == grandSon) son.couponNum += 1;
                });
              });
            }
            if(item.first_discount == "1"){
              if(item.first_pay_discount == "100"){
                item.first_value = "免单"
              }else{
                var d_num = (100 - Number(item.first_pay_discount))/10;
                console.log("d_num",d_num)
                item.first_value = "享" + d_num + "折"
              }
            }
          });
          this.parentOptionId = val.type_card_id;
        } else {
          this.rechangeData = "";
        }
      });
    },
    handleChangeCheck(val){
      this.checkedList = val;
    },
    selectPayment(i){
      this.payment_index = i;
      this.payment_code.forEach((item,index) => {
        if(index == i){
          item.select = true;
        }else{
          item.select = false;
        }
      })
    },
    handleConfirm(){
      this.showModal = false;
      Taro.navigateBack({delta: 3})
    },
    handleClose(){
      this.showModal = false;
    }
  }
}

</script>
